package examples.ejb.ejb20.basic.transaction;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import weblogic.ejbgen.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Hashtable;

/**
 * TransactionBean is a stateless Session Bean. This bean illustrates:
 * <ul>
 * <li> No persistence of state between calls to the Session Bean
 * <li> Looking up values from the Environment
 * </ul>
 *
 * @author Copyright (c) 1999-2008 by BEA Systems, Inc. All Rights Reserved.
 */
@EnvEntries({
    @EnvEntry(name = "WEBL",
              type = "java.lang.Double",
              value = "10.0"),
    @EnvEntry(name = "minLimit",
              type = "java.lang.Integer",
              value = "6"),
    @EnvEntry(name = "maxLimit",
              type = "java.lang.Integer",
              value = "15")
})
@FileGeneration(remoteClass = Constants.Bool.TRUE,
                localHome = Constants.Bool.FALSE,
                remoteHome = Constants.Bool.TRUE,
                remoteClassName = "Transaction",
                remoteHomeName = "TransactionHome",
                localClass = Constants.Bool.FALSE)
@JarSettings(ejbClientJar = "ejb20_basic_transaction_client.jar")
@JndiName(remote = "ejb20-transaction-TransactionHome")
@Session(maxBeansInFreePool = "1000",
         initialBeansInFreePool = "0",
         transTimeoutSeconds = "0",
         type = Session.SessionType.STATELESS,
         defaultTransaction = Constants.TransactionAttribute.REQUIRED,
         ejbName = "transaction",
         enableCallByReference = Constants.Bool.TRUE)
public class TransactionBean implements SessionBean {

  private static final boolean VERBOSE = false;
  private SessionContext ctx;
  private int minLimit;
  private int maxLimit;
  ///private static List<PasswordRec> listOfNames = new ArrayList<PasswordRec>();
  //private static List<String[]> listOfNames = new ArrayList<String[]>();
  
  private static Hashtable infoTable = new Hashtable();
  
  static {
		try {
			loadHashTable();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

  }
  
	private static final String REQUESTTEST = "C:/bea/wlserver_10.3/request.txt";
	private static int nextKey(){
		int cnt=1;
		String[] thisLine = (String[]) infoTable.get(cnt);
		while (thisLine!=null){
			cnt++;
			thisLine = (String[]) infoTable.get(cnt);
		}
		return(cnt);
	}

	private static void appendToFile(String theRecord){
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(REQUESTTEST, true));
			bw.write(theRecord);
			bw.newLine();
			bw.flush();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {                       // always close the file
			if (bw != null) try {
				bw.close();
			} catch (IOException ioe2) {
				ioe2.printStackTrace();
			}
		}
	}  
	@RemoteMethod()
	public String getTitle (int position){
		String[] thisRec = (String[]) infoTable.get(position);
		if (thisRec!=null) {
			return thisRec[0];
		}
		return "";
	}
	@RemoteMethod()
	public int getQuantity (int position){
		String[] thisRec = (String[]) infoTable.get(position);
		if (thisRec!=null) {
			return Integer.parseInt(thisRec[1]);
		}
		return 0;
	}
	@RemoteMethod()
	public String getName (int position){
		String[] thisRec = (String[]) infoTable.get(position);
		if (thisRec!=null) {
			return thisRec[2];
		}
		return "";
	}
	@RemoteMethod()
	public String getAddress (int position){
		String[] thisRec = (String[]) infoTable.get(position);
		if (thisRec!=null) {
			return thisRec[3];
		}
		return "";
	}
	@RemoteMethod()
	public String getOrganization (int position){
		String[] thisRec = (String[]) infoTable.get(position);
		if (thisRec!=null) {
			return thisRec[4];
		}
		return "";
	}

	private void printTable(){
		int cnt=1;
		String[] thisLine = (String[]) infoTable.get(cnt);
		while (thisLine!=null){
			System.out.printf("%s|%s|%s|%s|%s\n",thisLine[0],thisLine[1],thisLine[2],thisLine[3],thisLine[4]);
			cnt++;
			thisLine = (String[]) infoTable.get(cnt);
		}
	}
	
	@RemoteMethod()
	public boolean addRequest (String requestinfo){
		int theNextKey=nextKey();
		Pattern extPattern=Pattern.compile("\\*(.*)\\*(.*)\\*(.*)\\*(.*)\\*(.*)\\*",Pattern.CASE_INSENSITIVE);
		Matcher matcher = extPattern.matcher(requestinfo.trim());
		if (matcher.find()){
			String[] newRec = new String[5];
			newRec[0]= matcher.group(1);
			newRec[1]= matcher.group(2);
			newRec[2]= matcher.group(3);
			newRec[3]= matcher.group(4);
			newRec[4]= matcher.group(5);
			infoTable.put(theNextKey, newRec);	
			appendToFile(theNextKey+requestinfo);
			return(true);
		} else
			return false;
	}
	
	private static void loadHashTable() throws FileNotFoundException{
		String line=null;
		int thisID;
		//Pattern extPattern=Pattern.compile("(\\w*)\\*(\\w*)\\*(\\w*)\\*(\\w*)\\*(\\w*)\\*(\\w*)\\*",Pattern.CASE_INSENSITIVE);

		Pattern extPattern=Pattern.compile("(.*)\\*(.*)\\*(.*)\\*(.*)\\*(.*)\\*(.*)\\*",Pattern.CASE_INSENSITIVE);
		BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(
				new FileInputStream(REQUESTTEST))));	
		try {
			while ((line=reader.readLine())!=null){
				Matcher matcher = extPattern.matcher(line.trim());
				while (matcher.find()){
					String[] newRec = new String[5];
					thisID= Integer.parseInt(matcher.group(1));
					newRec[0]= matcher.group(2);
					newRec[1]= matcher.group(3);
					newRec[2]= matcher.group(4);
					newRec[3]= matcher.group(5);
					newRec[4]= matcher.group(6);
					infoTable.put(thisID, newRec);
				}
			}		
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
  
  // You might also consider using WebLogic's log service
  private void log(String s) {
    if (VERBOSE) System.out.println(s);
  } 
  
  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbActivate() {
    log("ejbActivate called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbRemove() {
    log("ejbRemove called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbPassivate() {
    log("ejbPassivate called");
  }

  /**
   * Sets the session context.
   *
   * @param ctx               SessionContext Context for session
   */
  public void setSessionContext(SessionContext ctx) {
    log("setSessionContext called");
    this.ctx = ctx;
  }

  /**
   * This method corresponds to the create method in the home interface
   * "TransactionHome.java".
   * The parameter sets of the two methods are identical. When the client calls
   * <code>TransactionHome.create()</code>, the container allocates an instance of 
   * the EJBean and calls <code>ejbCreate()</code>.
   *
   * @exception               javax.ejb.CreateException if there is
   *                          a communications or systems failure
   * @see                     examples.ejb.ejb20.basic.statelessSession.Trader
   */
  public void ejbCreate () throws CreateException {
//    log("ejbCreate called");
//
//    try {
//      InitialContext ic = new InitialContext();
//
//      Integer tl = (Integer) ic.lookup("java:/comp/env/maxLimit");
//      Integer t2 = (Integer) ic.lookup("java:/comp/env/minLimit");
//    
//      maxLimit = tl.intValue();
//      minLimit = t2.intValue();
//    } catch (NamingException ne) {
//      throw new CreateException("Failed to find environment value "+ne);
//    }
  }

}